package com.example.studentaihouduan.Controller;

import com.example.studentaihouduan.JWT.JwtTokenUtil;
import com.example.studentaihouduan.entity.User;
import com.example.studentaihouduan.service.Serviceimpl.UserDetailsServiceImpl;
import com.example.studentaihouduan.service.Serviceimpl.UserServiceImpl;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/auth")
@EnableCaching
public class AuthController {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private UserDetailsServiceImpl userDetailsService;

    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private UserServiceImpl userService;

    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody LoginRequest loginRequest) {
        // 认证
        Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(
                        loginRequest.getUsername(),
                        loginRequest.getPassword()
                )
        );

        SecurityContextHolder.getContext().setAuthentication(authentication);

        // 生成token
        UserDetails userDetails = userDetailsService.loadUserByUsername(loginRequest.getUsername());
        String token = jwtTokenUtil.generateToken(userDetails);

        // 获取完整的用户信息（包含角色）
        User user = (User) userDetails;

        // 返回完整用户信息
        return ResponseEntity.ok(new JwtResponse(
                token,
                user.getId(),
                user.getUsername(),
                user.getNickname(),
                user.getEmail(),
                user.getPhone(),
                user.getAvatar(),
                user.getStatus(),
                user.getRoles().stream()
                        .map(role -> role.getCode()) // 修改为 lambda 表达式
                        .collect(Collectors.toList()),
                user.getLastLoginTime(),
                user.getLastLoginIp()
        ));
    }

    @PostMapping("/register")
    public ResponseEntity<?> register(@RequestBody RegisterRequest registerRequest) {
        User user = new User();
        user.setUsername(registerRequest.getUsername());
        user.setPassword(passwordEncoder.encode(registerRequest.getPassword())); // 需要注入PasswordEncoder
        user.setNickname(registerRequest.getNickname());
        user.setEmail(registerRequest.getEmail());
        user.setPhone(registerRequest.getPhone());
        user.setStatus(true); // 默认启用状态

        // 添加时间字段
        Date now = new Date();
        user.setCreateTime(now);
        user.setUpdateTime(now);

        userService.save(user);

        return ResponseEntity.ok("注册成功");
    }

    // 请求和响应DTO
    @Data
    static class LoginRequest {
        private String username;
        private String password;
    }

    @Data
    static class JwtResponse {
        private String token;
        private Long id;
        private String username;
        private String nickname;
        private String email;
        private String phone;
        private String avatar;
        private Boolean status;
        private List<String> roles;
        private Date lastLoginTime;
        private String lastLoginIp;

        public JwtResponse(String token, Long id, String username, String nickname,
                           String email, String phone, String avatar, Boolean status,
                           List<String> roles, Date lastLoginTime, String lastLoginIp) {
            this.token = token;
            this.id = id;
            this.username = username;
            this.nickname = nickname;
            this.email = email;
            this.phone = phone;
            this.avatar = avatar;
            this.status = status;
            this.roles = roles;
            this.lastLoginTime = lastLoginTime;
            this.lastLoginIp = lastLoginIp;
        }
    }
    @Data
    static class RegisterRequest {
        private String username;
        private String password;
        private String nickname;
        private String email;
        private String phone;
    }

}